/*************************************************************************
	> File Name: wait.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Mon 07 Jul 2014 03:01:03 PM CST
 ************************************************************************/
/*
 * 用fork创建多个子进程,在子进程执行相应操作后退出
 * 父进程仅仅用来创建子进程(do nothing)
 * 在fork()后使用wait来判断子进程是否已经退出,并执行
 * 相应操作,最后退出程序
 *
 * 缺点是:必须等待每个子进程退出,否则会阻塞操作
 */

#include "head.h"
int main(int argc,char *argv[])
{
    pid_t child;
    int children;
    int i,num=0;
    int j,k;

    children=(argc>1)?atoi(argv[1]):1;
    
    for(i=0;i<children;i++)
    {
        switch(fork())
        {
            case -1:
                err("fork");
            case 0:
                printf("(child) pid: %ld\n",(long)getpid());
                for(j=0;j<65534;j++)
                    for(k=0;k<65534;k++);
                sleep(2);
                _exit(0);
            default:
                break; // do nothing, just create child
        }
    }
    for(;;)
    {
        child=wait(NULL); // wait for each child to exit
        if(child==-1)
        {
            if(errno==ECHILD)
            {
                printf("all childern have exited\n");
                _exit(0);
            }
        
             else
            {
                sleep(1);
                printf("\e[34m still waitting\e[0m\n");
            }
        }

            num++;

            printf("(child) \e[32m<--:\e[0m\e[44m %ld \e[0m\e[32m:-->\e[0m dead number: %d\n",child,num);
    }
}
